package com.typhoon.extend.dao;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.typhoon.extend.entity.User;

/**
 * 用户dao
 * 
 * @author Typhoon
 *
 */
@Repository("userDao")
public class UserDao extends BaseDao implements ICommonDao<User, Long> {

	private static final String TABLE_USER = "User";

	@Resource
	private JdbcTemplate extendJdbc;

	@Override
	public User queryByPrimaryKey(Long primaryKey) {
		return this.queryByPrimaryKey(extendJdbc, TABLE_USER, primaryKey, User.class);
	}

	@Override
	public int deleteByPrimaryKey(Long primaryKey) {
		return this.deleteByPrimaryKey(extendJdbc, TABLE_USER, "id", primaryKey);
	}

	@Override
	public User get(Object paramObject) {
		return this.get(extendJdbc, TABLE_USER, paramObject, User.class);
	}

	@Override
	public List<User> list(Map<String, Object> paramMap) {
		return this.list(extendJdbc, TABLE_USER, paramMap, User.class);
	}

	@Override
	public List<User> list(Object paramObject) {
		return this.list(extendJdbc, TABLE_USER, paramObject, User.class);
	}

	@Override
	public int update(User paramE) {
		return this.updateByPrimaryKey(extendJdbc, paramE, TABLE_USER);
	}

	@Override
	public long count(Map<String, Object> paramMap) {
		return this.count(extendJdbc, TABLE_USER, paramMap);
	}

	@Override
	public long count(Object paramObject) {
		return this.count(extendJdbc, TABLE_USER, paramObject);
	}

	@Override
	public User save(User paramE) {
		return this.addObjForKey(extendJdbc, TABLE_USER, paramE, "id");
	}

	public User queryByAccount(Long accountId) {
		StringBuilder sql = new StringBuilder();
		sql.append("	SELECT	");
		sql.append("		u.*	");
		sql.append("	FROM	");
		sql.append("		`User` u	");
		sql.append("	LEFT JOIN AccountOfUser aou ON u.id = aou.userId	");
		sql.append("	WHERE	");
		sql.append("		aou.accountId = ?		");
		sql.append("		LIMIT 1	");
		List<User> list = this.extendJdbc.query(sql.toString(), BeanPropertyRowMapper.newInstance(User.class), accountId);
		if(null == list || list.isEmpty())
		{
			return null;
		}
		return list.get(0);
	}

}
